//package com.bright.hxj.qchz.service.thread;
//
//import com.bright.hxj.qchz.pojo.bo.DuijieReturnMsg;
//import com.bright.hxj.qchz.pojo.po.Duijie_ShiJieShouUser;
//import com.bright.hxj.qchz.service.Duijie_ShengJieShou_QCHZManager;
//import com.bright.hxj.qchz.service.TaskManager;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.json.JSONArray;
//import org.json.JSONObject;
//
//import java.util.List;
//import java.util.concurrent.*;
//
///**
// * 获取区数据
// */
//@RequiredArgsConstructor
//@Slf4j
//public class Duijie_QCHZ_ProcessAsyncThread implements Callable<DuijieReturnMsg> {
//
//    private final String taskId;
////    private final String xmbm; //项目编码
////    private final String userName;
//    private final String methodName;
//    private final String ztId;
//
//    private final Duijie_ShiJieShouUser user;
//
//    private final JSONObject jsonObject;
//
////    private final JdbcTemplateUtil jdbcTemplate;
//
//    private final Duijie_ShengJieShou_QCHZManager qchzManager;
//    private final TaskManager taskManager;
//
//
////    public boolean isTest = false; // 是否测试
//
////    @Value("${duijie.maxThreadSize:30}")
////    private int maxThreadSize; // 线程池的最大大小
////    @Value("${duijie.maxQueueSize:500}")
////    private int maxQueueSize; // 排队队列最大大小
////    static {
////        String value = PropertiesUtil.getValue("duijie.maxThreadSize");
////        if (value == null) {
////            maxThreadSize = 30;
////        } else {
////            maxThreadSize = Integer.parseInt(value);
////        }
////
////        value = PropertiesUtil.getValue("duijie.maxQueueSize");
////        if (value == null) {
////            maxQueueSize = 500;
////        } else {
////            maxQueueSize = Integer.parseInt(value);
////        }
////    }
//
////    public Duijie_QCHZ_ProcessAsyncThread(String taskId, Duijie_ShiJieShouUser user, String methodName, String ztId,
////                                          JSONObject jsonObject, Duijie_ShengJieShou_QCHZManager qchzManager, ThreadPoolTaskExecutor executorService) {
////        this.taskId = taskId;
//////        this.xmbm = xmbm;
////        this.user = user;
////        this.methodName = methodName;
////        this.ztId = ztId;
//////        this.jdbcTemplate = jdbcTemplate;
////        this.jsonObject = jsonObject;
////        this.qchzManager = qchzManager;
////    }
//
//
//    @Override
//    public DuijieReturnMsg call() throws Exception {
//        DuijieReturnMsg rvalue;
//        System.out.println(taskId + " begin...");
//        rvalue = call_process();
//        System.out.println(taskId + " end.");
//
//        return rvalue;
//    }
//
//    private DuijieReturnMsg call_process() {
//        DuijieReturnMsg msgInner = null;
//
//        try {
//            List<String> errorMsg = qchzManager.checkDataValid(jsonObject, methodName);
//            if (errorMsg.size() > 0) {
//                msgInner = new DuijieReturnMsg("数据校验未通过，请检查！", errorMsg);
//            }
//
//            if (msgInner == null) {
//                // 将数据存进数据库
//                msgInner = qchzManager.insertOrUpdate(user, jsonObject, methodName);
////                if (!DuijieReturnMsg.isSuccess(msgInner)) {
////                    // 这个分支是数据校验通过 已经在往数据库里存了 要出错也是只给我们自己内部人员看的错误 用抛异常的方式
////                    throw new RuntimeException("数据保存时出错：" + msgInner.getNoRoleInfo());
////                }
//                // 存数据库也会出现 字段类型不对 字段不应为空 等等需要第三方处理的情况
//            }
//
//            // 先看异步任务表中是否有这个taskId，如果没有，可能是该线程执行太快，主线程createTask还没执行完导致表没这个任务号，休眠等待
//            int tryCount = 0;
//            while (tryCount <= 300 && taskManager.getTaskDataByTaskId(taskId, "1", "").size() == 0) {
//                System.out.println("正在等待createTask执行：" + taskId);
//                TimeUnit.MILLISECONDS.sleep(100);
//                tryCount++;
//            }
//            if (tryCount > 300) {
//                log.error(taskId + "等待30秒后仍未能在taskAsync中找到任务号 运行结果：" + DuijieReturnMsg.isSuccess(msgInner) + " " + msgInner.getNoRoleInfo());
//                return msgInner;
//            }
//
//            // 任务执行完成 更新数据库中的任务状态
//            if (DuijieReturnMsg.isSuccess(msgInner)) {
//                taskManager.updateTaskStatus(taskId, user.getUserName(), TaskManager.ASYNC_TASK_SUCCESS, "操作成功！", null);
//                log.info(user.getUserName() + "：" + taskId + "线程执行操作成功！");
//            } else {
//                if (msgInner.getNoRoleInfoList() != null) {
//                    // 数据校验不通过
//                    JSONArray errorInfoList = new JSONArray(msgInner.getNoRoleInfoList());
//                    taskManager.updateTaskStatus(taskId, user.getUserName(), TaskManager.ASYNC_TASK_CHECK_FAILED,
//                            errorInfoList.toString(), null);
//                    log.info(user.getUserName() + "：" + taskId + "线程执行完成！数据校验出错：" + errorInfoList);
//                } else {
//                    // 其他异常情况
//                    taskManager.updateTaskStatus(taskId, user.getUserName(), TaskManager.ASYNC_TASK_ERROR,
//                            msgInner.getNoRoleInfo(), null);
//                    log.info(user.getUserName() + "：" + taskId + "线程执行完成！返回异常：" + msgInner.getNoRoleInfo());
//                }
//            }
//
//        } catch (Throwable error) {
//            // 任务出错 更新数据库中的任务状态
//            taskManager.updateTaskStatus(taskId, user.getUserName(), TaskManager.ASYNC_TASK_ERROR,
//                    "执行线程出错！请联系管理员！", error.getMessage());
//
//            log.error(taskId + "执行线程出错：", error);
////            System.out.println(taskId + "出错！" + error.getMessage());
//            return new DuijieReturnMsg("执行线程出错！请联系管理员！");
//        }
//
//        return msgInner;
//    }
//
//    private DuijieReturnMsg call_test() {
//        // 测试方法
//        return null;
//    }
//
//
////    private ExecutorService executorService;
////    public synchronized static ExecutorService getExecutorService() {
////        // 创建线程池
////        if(executorService == null) {
//////            executorService = Executors.newFixedThreadPool(maxThreadSize);
////            executorService = new ThreadPoolExecutor(5, maxThreadSize, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(maxQueueSize));
////
////            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
////                @Override
////                public void run() {
////                    if (executorService != null) {
////                        executorService.shutdown();
////                        System.out.println("线程池executorService已关闭！");
////                    }
////                }
////            }));
////
////        }
////        return executorService;
////    }
//
////    public synchronized static ExecutorService getExecutorService(int maxThreadSize) {
//        // 测试用 指定生成的最大线程数
////        if (executorService != null) {
////            executorService.shutdown();
////        }
////        executorService = Executors.newFixedThreadPool(maxThreadSize);
////
////        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
////            @Override
////            public void run() {
////                if (executorService != null) {
////                    executorService.shutdown();
////                    System.out.println("线程池executorService已关闭！");
////                }
////            }
////        }));
////        return executorService;
////        return null;
////    }
//
////    private DuijieReturnMsg createTask(String taskId, Object userName, String methodName, String ztId) {
////
////        try {
////            jdbcTemplate.update("insert into taskAsync(taskId, userName, methodName, years, ztId, runFlag, creator, createDate) " +
////                    "values(?,?,?,?,?,?,?,?)", new Object[]{taskId, userName, methodName, 2022, ztId, true, userName, DateUtil.getCurrDate()});
////
////        } catch (Exception e) {
////            log.error("创建任务时出错 ", e);
////            return new DuijieReturnMsg("创建任务时出错：" + e.getMessage());
////        }
////
////        return new DuijieReturnMsg(true, taskId);
////    }
////
////    private void updateTaskStatus(String taskId, Object userName, boolean successFlag, String msg, JSONArray data) {
//////        Date beginDate;
////        try {
////            // 计算耗时
//////            List<List<Object>> lists = jdbcTemplate.queryForListList("select createDate from taskAsync where taskId=?", new Object[]{taskId});
//////            if (lists.size() > 0) {
//////                Object createDateObj = lists.get(0).get(0);
//////                beginDate = DateUtil
//////            }
////
////            String dataStr = data == null ? null : data.toString();
////            jdbcTemplate.update("update taskAsync set okFlag=?, content=?, data=?, writer=?, writeDate=? where taskId=?",
////                    new Object[]{successFlag, msg, dataStr, userName, DateUtil.getCurrDate(), taskId});
////        } catch (Exception e) {
////            log.error("更新任务状态时出错 ", e);
//////            return new DuijieReturnMsg("更新任务状态时出错：" + e.getMessage());
////        }
////
//////        return null;
////    }
//
//
//
//
//
//
////    public static void main(String[] args) {
////        Dist dist = new Dist();
////        dist.setDistNo("0106");
////
////        String url = "http://localhost:8071/toShi/duijieToShiTongji.do?method=tongji";
////
////        // 创建一个容量为5的线程池
////        ExecutorService executorService = Duijie_QCHZ_ProcessAsyncThread.getExecutorService();
////
////
////
//////        List<Future<ReturnInfo_QuDataThread>> futureTasks = new CopyOnWriteArrayList<Future<ReturnInfo_QuDataThread>>();
//////        for( int i=1; i<=1; i++) {
//////            Callable c = new Duijie_QCHZ_ProcessAsyncThread(i, "name" + i, true, dist, null, url);
////////            futureTasks.add(new FutureTask<ReturnInfo_QuDataThread>(c));
//////
//////            futureTasks.add(executorService.submit(c));
//////        }
//////
//////        try {
//////            for(int i=0; i<futureTasks.size(); i++) {
//////                ReturnInfo_QuDataThread returnInfo_quDataThread = futureTasks.get(i).get();
//////
//////                System.out.println("------------------");
//////                System.out.println(futureTasks.get(i).get().getName());
//////
//////                System.out.println(returnInfo_quDataThread.getRoleInfo());
//////                System.out.println(returnInfo_quDataThread.getQuData_tongji());
//////                System.out.println(returnInfo_quDataThread.getQuData_tongjiSub());
//////            }
//////
//////
//////        } catch (InterruptedException e) {
//////            e.printStackTrace();
//////        } catch (ExecutionException e) {
//////            e.printStackTrace();
//////        }
////
////        executorService.shutdown();
////    }
//}
